package com.oocl.euc.core.maintenance.service;

import com.oocl.euc.core.maintenance.model.Role;
import com.oocl.euc.core.maintenance.model.RoleAuth;
import com.oocl.euc.core.maintenance.model.SupportGroup;
import com.oocl.euc.core.maintenance.model.Users;
import com.oocl.euc.core.maintenance.repository.RoleRepository;
import com.oocl.euc.framework.base.persistence.IBaseRepository;
import com.oocl.euc.framework.base.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleService extends BaseService<Role, Long> {

    @Autowired RoleRepository roleRepository;

    @Autowired RoleAuthService roleAuthService;

    @Autowired UsersService usersService;

    @Autowired SupportGroupService supportGroupService;

    @Override
    protected IBaseRepository<Role, Long> getRepository() {
        return roleRepository;
    }

    public Role addAuthorizationByRoleIdAndDomainIdOrGroupName(Long roleId, String domainIdOrGroupName) {
        Role role = this.findOne(roleId);
        String domainIdOrGroupNameUpperCase = domainIdOrGroupName.toUpperCase();
        Users user = usersService.findByDomainId(domainIdOrGroupNameUpperCase);
        if (user != null) {
            RoleAuth roleAuth = new RoleAuth();
            roleAuth.setUsers(user);
            role.getRoleAuths().add(roleAuth);
            roleRepository.save(role);
            return role;
        }else {
            SupportGroup supportGroup = supportGroupService.findByGroupName(domainIdOrGroupNameUpperCase);
            if(supportGroup != null){
                RoleAuth roleAuth = new RoleAuth();
                roleAuth.setSupportGroup(supportGroup);
                role.getRoleAuths().add(roleAuth);
                roleRepository.save(role);
                return role;
            }
            return null;
        }
    }

    public void deleteAuthorizationByRoleAuthorizationId(Long roleAuthorizationId) {
        roleAuthService.delete(roleAuthorizationId);
    }

    public Role update(Role role) {
        Role newRole = this.findOne(role.getId());
        newRole.setRoleName(role.getRoleName());
        newRole.setRoleDesc(role.getRoleDesc());
        roleRepository.save(newRole);
        return newRole;
    }

    public List<Role> findRoleByStaffId(String staffId) {
        return roleRepository.findRoleByStaffId(staffId);
    }
}
